package com.zoe.vhr.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zoe.vhr.util.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/26
 * @Description 权限不足处理器
 */
@Configuration
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        R<String> failed = R.forbidden("权限不足 MyAccessDeniedHandler");
        PrintWriter writer = resp.getWriter();
        String s = new ObjectMapper().writeValueAsString(failed);
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
